package logic

import (
	"context"
	"errors"
	"user_srv/models"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type AthRealnameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAthRealnameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AthRealnameLogic {
	return &AthRealnameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AthRealnameLogic) AthRealname(in *user.AthRealnameRequest) (*user.AthRealnameResponse, error) {
	// todo: add your logic here and delete this line

	var i models.UserIdentity
	i.UserId = in.UserId
	err := i.GetRealnameByUserId()
	if err != nil {
		logx.Error("实名失败:查找用户ID失败", err)
		return nil, err
	}

	if i.ID > 0 {
		logx.Error("实名失败:", errors.New("已实名"))
		return nil, errors.New("已实名")
	}

	if !pkg.ArhRealname(in.IdCard, in.Realname) {
		logx.Error("实名失败:", errors.New("调用第三方接口错误"))
		return nil, errors.New("调用第三方接口错误")
	}

	i.IdCard = in.IdCard
	i.Realname = in.Realname
	err = i.Create()
	if err != nil {
		logx.Error("实名失败:数据库存入信息失败", err)
		return nil, err
	}

	return &user.AthRealnameResponse{}, nil
}
